#import "Plot.h"
#import "PlotView.h"
#import <appkit/drag.h>
#import <appkit/Pasteboard.h>
#import <bsd/strings.h>		// for declaration of strchr

/*
 * Dragging code for PlotView.
 */

@implementation PlotView(Drag)


/* Method to search through Pasteboard types lists (from Draw Example). */

BOOL IncludesType(const NXAtom *types, NXAtom type)
{
    if (types) {
      while (*types) {
	if (*types++ == type) return YES;
      }
    }
    return NO;
}


/*
 * Just see if there is a file there we can copy.  Code taken from
 * the Draw Example in NextDeveloper/Examples.
 */
- (NXDragOperation)draggingEntered:(id <NXDraggingInfo>)sender
{
  Pasteboard *pboard;
  NXDragOperation sourceMask;

  sourceMask = [sender draggingSourceOperationMask];
  pboard = [sender draggingPasteboard];

  if (sourceMask & NX_DragOperationCopy) {
    if (IncludesType([pboard types], NXFilenamePboardType)) { // why?
      return NX_DragOperationCopy;
    }
  }

  return NX_DragOperationNone;
}


/*
 * Try to plot any file(s) that have been dragged onto us.
 */
- (BOOL)performDragOperation:(id <NXDraggingInfo>)sender
{
  Pasteboard *pboard;
  char	 *stringPosition, *filename, *data;
  int    length;

  pboard = [sender draggingPasteboard];

  if (IncludesType([pboard types], NXFilenamePboardType)) {
    [pboard readType:NXFilenamePboardType data:&data length:&length];
    filename = data;
    while (filename) {
      stringPosition = strchr(filename, '\t'); // returns first tab or NULL
      if (stringPosition) {
	*stringPosition = '\0';
      }
      [plotParam openFile:filename :filename];
      filename = (stringPosition ? ++stringPosition : NULL);
    }
    [pboard deallocatePasteboardData:data length:length];
    return YES;
  }
  else {
    return NO;
  }
}

@end
